import {cardCache,deepClone,promptBox,toast} from "nc-lightapp-front";
let {setDefData, getDefData } = cardCache;
import AssidModalRedner from '../components/AssidModalRedner'
import pubUtil from './pubUtil'
import {cacheTools} from 'nc-lightapp-front';
class CardPageController{
    constructor(main, props, meta) {
        this.main = main;
        this.props = props;
        this.dataSource = meta.dataSource;
        this.paginationShowClassName = meta.paginationShowClassName;
        this.headId = meta.headId || 'head';
        this.bodyId = meta.bodyId || 'body';
        this.formId = meta.formId || '';
        this.listIds = meta.listIds || [];
        this.listButtonAreas = meta.listButtonAreas || {};
        this.browseButtons = ['Add', 'Edit', 'Delete','Refresh','Assist', ...meta.browseButtons || []];
        this.editButtons = ['Save', 'SaveAdd','Cancel', 'AddLine','Copy','CopyToEnd', ...meta.editButtons || []];
        this.disabledButtons = ['Edit', 'Delete',...meta.editButtons || []];//, 'Assist'
        this.disabledListButtons = ['AddLine', 'DelLine','Copy', ...meta.editButtons || []];
        this.listUrl = meta.listUrl || '';
        this.listPageCode = meta.listPageCode || '';
        this.deleteConformModalCode = meta.deleteConformModalCode || 'delete';
        this.pkField = meta.pkField || '';
        //复制标志
        this.copyFlag=true;
        // 内部变量
        this.cacheData = getDefData('cacheData_Key', this.dataSource) || {};
        this.id = this.props.getUrlParam('id');
        // 页面初始化
        this.initTemplate();
    }
    loadDefaultData(){
        
    }
    /**
     * 设置当前页ID
     * @param {*} value 
     */
    setId(value){
        this.id=value;
    }
    /**
     * 翻页处理
     */
    pageInfoClick(data){
        this.setId(data)
        this.props.setUrlParam({id:data});
        // this.props.cardPagination.setCardPaginationId({id:data});
        this.queryData(this.id);
    }
    /**
     * 取得当前条显示按钮
     * @param {*} listAreaId 
     * @param {*} text 
     * @param {*} record 
     * @param {*} index 
     */
    getListButtons(listAreaId, text, record, index){
        return ['DelLine','insertLine',"Copy","CopyToThis"];
    }
    /**
     * 添加处理列
     * @param {*} listAreaId 
     */
    addOpr(listAreaId){
        let meta = this.props.meta.getMeta();
        let event = {
            label: this.main.state.json['2002-0002'],
            attrcode: 'opr',
            itemtype: 'customer',
            visible: true,
            width: '180px',
            fixed: 'right',
            render: (text, record, index) =>{
                return this.props.button.createOprationButton(this.getListButtons(), {
                    area: this.listButtonAreas[listAreaId],
                    buttonLimit: 3,
                    onButtonClick: (props, btnKey) => {
                        this.listButtonClick(listAreaId, btnKey, record, index);
                    }
                });
            }
        };
        meta[listAreaId].items.push(event);
        this.props.meta.setMeta(meta);
    }
    /**
     * 移除处理列
     * @param {*} listAreaId 
     */
    removeOpr(listAreaId){
        if(this.props.meta.getMeta()[listAreaId].items[this.props.meta.getMeta()[listAreaId].items.length-1].attrcode == 'opr'){
            this.props.meta.getMeta()[listAreaId].items.pop();
        }
    }
    /**
     * 页面状态变更处理
     * @param {*} state 
     */
    setPageState(state){
        switch(state){
            case 'browse':
                this.main.setState({[this.paginationShowClassName]: 'show'});
                this.props.button.setButtonVisible(this.editButtons, false);
                this.props.button.setButtonVisible(this.browseButtons, true);
                this.props.form.setFormStatus(this.formId, 'browse');
                this.listIds.map((one)=>{
                    this.props.editTable.setStatus(one, 'browse');
                    this.removeOpr(one);
                })
                this.props.setUrlParam({status:'browse'});
                let id = this.props.getUrlParam('id')
                this.setButtonStatus(this.disabledButtons, id ? false : true)
                this.copyFlag=true;
            break;
            case 'add':
                this.main.setState({[this.paginationShowClassName]: 'hide'});
                this.props.button.setButtonVisible(this.browseButtons, false);
                this.props.button.setButtonVisible(this.editButtons, true);
                this.props.form.setFormStatus(this.formId, 'add');
                this.listIds.map((one)=>{
                    this.props.editTable.setStatus(one, 'edit');
                    this.addOpr(one);
                })
                this.props.setUrlParam({status:'add'});
            break;
            case 'edit':
                this.main.setState({[this.paginationShowClassName]: 'hide'});
                this.props.button.setButtonVisible(this.browseButtons, false);
                this.props.button.setButtonVisible(this.editButtons, true);
                this.props.form.setFormStatus(this.formId, 'edit');
                this.listIds.map((one)=>{
                    this.props.editTable.setStatus(one, 'edit');
                    this.addOpr(one);
                })
                this.props.setUrlParam({status:'edit'});
            break;
        }
    }
    /**
     * 初始化模板
     * @param {*} meta 
     */
    initMeta(meta){
       
    }
    /**
     * 初始化参照过滤条件
     * @param {*} meta 
     */
    initRefParam(meta){
          
    }
    /**
     * 页面初始化
     */
    initTemplate(){
        this.props.createUIDom(
            {},
            (data) => {
                let meta = data.template;
                meta.isNeedVersion=this.props.isNeedVersion;
                this.initMeta(meta);
                this.initRefParam(meta);
                window.setTimeout(() => {
                    this.props.meta.setMeta(meta);
                    this.props.button.setButtons(data.button);
                    this.initTemplateSetPageState(data);
                }, 1);
            }
        )
    }
    /**
     * 初始化页面状态
     */
    initTemplateSetPageState(data){
        let pageStatus = this.props.getUrlParam('status');
        this.setPageState(pageStatus);
        if(pageStatus == 'browse'){
            this.queryData(this.id);
        }else if(pageStatus == 'edit'){
            this.queryData(this.id);
        }else if(pageStatus == 'add'){

        }
    }

    queryData(id){

    }
    setPageData(data){
        if(data != null && data.data != null){
            this.props.form.setAllFormValue({[this.formId]: data.data[this.headId][this.formId] || {rows:[]}});
            this.listIds.map((one)=>{
                if((data.data[this.bodyId] || {})[one] != null){
                    this.props.editTable.setTableData(one, data.data[this.bodyId][one] || {rows:[]});    
                }else{
                    this.props.editTable.setTableData(one, {rows:[]});
                }
            })
        }else{
            this.props.form.EmptyAllFormValue(this.formId);
            this.listIds.map((one)=>{
                this.props.editTable.setTableData(one, {rows:[]});
            })
            this.setButtonStatus(this.disabledButtons, true)
        }
    }
    /**
     * 表头按钮事件
     * @param {string buttonId} 按钮ID  
     */
    headButtonClick(buttonId){
        switch(buttonId){
            case 'Add':
                this.Add();
            break;
            case 'Edit':
                this.Edit();
            break;
            case 'Delete':
                this.Delete();
            break;
            case 'Cancel':
            promptBox({
                color:"warning",
                title: this.main.state.json['2002-0011'],
                content: this.main.state.json['2002-0012'],
                beSureBtnClick: this.Cancel.bind(this)
                });
                //this.Cancel();
            break;
            case 'Save':
                this.Save();
            break;
            case 'AddLine':
                this.AddLine();
            break;
            case 'DelLine':
                this.DelTableLine();
            break;
            case 'Refresh':
                this.Refresh();
            break;
            case 'SaveAdd':
            this.SaveAdd();
            break;
            case 'Copy':
                this.CopyAll();
            break;
            case 'CopyToEnd':
                this.CopyToEnd();
            break;
            default:
            this[buttonId]();
        }
    }
    /**
     * 清空页面数据
     */
    clearPageData(){
        this.props.form.EmptyAllFormValue(this.formId);
        this.listIds.map((one)=>{
            this.props.editTable.setTableData(one, {rows:[]});
        })
    }
    /**
     *新增按钮事件
     */
    Add(){
        this.props.form.EmptyAllFormValue(this.formId);
        this.listIds.map((one)=>{
            this.props.editTable.setTableData(one, {rows:[]});
        })
        this.setPageState('add');
    }
    /**
     * 删除确认
     */
    Delete(){
        promptBox({
            color:"warning",
            title: this.main.state.json['2002-0013'],
            content: this.main.state.json['2002-0014'],
            beSureBtnClick: this.doDelete.bind(this)
        });
    }
    /**
     * 删除事件
     */
    doDelete(){
        
    }
    /**
     * 删除回掉方法
     */
    callBackDelete(){
        pubUtil.pushTo(this.props, this.listUrl,{
            appcode: this.props.getSearchParam('c'),
            pagecode: this.listPageCode
        });
    }
    /**
     * 修改按钮事件
     */
    Edit(){
        this.setPageState('edit');
    }
    /**
     * 取消按钮事件
     */
    Cancel(){
        this.props.form.cancel(this.formId);
        this.listIds.map((one)=>{
            this.props.editTable.cancelEdit(one);
        })
        this.setPageState('browse');
    }
    /**
     * 保存按钮事件
     */
    Save(){
        let checkFlag = this.props.form.isCheckNow(this.formId);
        this.listIds.map((one)=>{
            // TODO:平台问题，删除的也进行了合规性校验，导致出错
            // if(!this.props.editTable.getAllRows(one)){
            //     checkFlag = false;
            // }
        })
        if(checkFlag){
            let data = {};
            data[this.formId] = this.props.form.getAllFormValue(this.formId);
            this.listIds.map((one)=>{
                data[one] = this.props.editTable.getAllData(one);
            })
            this.doSave(data);
        }
        
    }
    /**
     * 保存动作
     * @param {*data} 页面数据
     */
    doSave(data){

    }
    /**
     * 保存回掉方法
     * @param {*data} 返回数据
     */
    callBackSave(data){
        if(this.pkField && data.data){
            this.setId(data.data[this.headId][this.formId].rows[0].values[this.pkField].value);
            let pk_org = data.data[this.headId][this.formId].rows[0].values['pk_org']; 
            let from_globle = (this.formId == 'notrecaccrelationset') ? (pk_org && pk_org.value == 'GLOBLE00000000000000' ? {from_globle: 'Y'} : {from_globle: ''}) : {};
            this.props.setUrlParam({
                id:data.data[this.headId][this.formId].rows[0].values[this.pkField].value,
                status: 'browse',
                ...from_globle
            });
        }
        this.setPageState('browse');
        this.setPageData(data);
        pubUtil.showMeggage(this.props, pubUtil.MESSAGETYPE.SAVE,this);
    }
    /**
     * 增行按钮事件
     */
    AddLine(){
        this.listIds.map((one)=>{
            this.props.editTable.addRow(one);
        })
    }
    /**
     * 列表按钮事件
     */
    listButtonClick(AreaId, actionId, data, index){
        switch(actionId){
            case 'DelLine':
                this.DelLine(AreaId, data, index);
            break;
            case 'Copy':
                this.Copy(AreaId, data, index);
            break;
            case 'CopyToThis':
                this.CopyToThis(AreaId, data, index);
            break;
            case 'insertLine':
                this.insertLine(AreaId, data, index);
            break;
        }
    }
    /**
     * 行删除事件
     * @param {*} AreaId 
     * @param {*} data 
     * @param {*} index 
     */
    DelTableLine(){
        let data = {};
        let AreaId='';
        this.listIds.map((one)=>{
            data[one] = this.props.editTable.getCheckedRows(one);
            AreaId=one;
        })
        let allIndex=[];
        if(data[AreaId].length>0){
            for(let i=0;i<data[AreaId].length;i++){
                allIndex.push(data[AreaId][i].index);
            }
            this.props.editTable.deleteTableRowsByIndex(AreaId, allIndex);
         } else{
            pubUtil.showMeggage(this.props, pubUtil.MESSAGETYPE.WARNING,this);
        }
        this.setButtonStatus(['DelLine','Copy'],true);
    }
    /**
     * 行删除事件
     * @param {*} AreaId 
     * @param {*} data 
     * @param {*} index 
     */
    DelLine(AreaId, data, index){
        // this.props.editTable.delRow(AreaId, index);
        this.props.editTable.deleteTableRowsByIndex(AreaId,index);
    }
    /**
     *复制按钮事件
     */
    CopyAll(){
        this.listIds.map((one)=>{
            let selectRows=this.props.editTable.getCheckedRows(one);
            if(selectRows.length>0){
                cacheTools.set('copyData', selectRows);
                this.copyFlag=false;
                this.getListButtons();
            }

        })
        this.setButtonStatus(['DelLine','Copy'],true);
    }
    /**
     * 行复制事件
     * @param {*} AreaId 
     * @param {*} data 
     * @param {*} index 
     */
    Copy(AreaId, data, index){
        this.props.editTable.pasteRow(AreaId, data,index);
    }
    /**
     * 粘贴至此事件
     * @param {*} AreaId 
     * @param {*} data 
     * @param {*} index 
     */
    CopyToThis(AreaId, data, index){
        // let  cachedata = cacheTools.get('copyData');
        // let clone = deepClone(cachedata);
        // // let number=this.props.editTable.getNumberOfRows(AreaId);
        // let datas=[];
        // if(clone!=null){
        //     for(let i=0;i<clone.length;i++){
        //         clone[i].data.values.pk_appdetail={display:null,value:null};
        //         datas.push({values:clone[i].data.values});
        //     }
        // }
        // this.props.editTable.insertRowsAfterIndex(AreaId, datas,index);
    }

    CopyToEnd(){
        let  cachedata = cacheTools.get('copyData');
        let clone = deepClone(cachedata);
        let number;
        this.listIds.map((one)=>{
            number=this.props.editTable.getNumberOfRows(one);
            let datas=[];
            if(clone!=null){
                for(let i=0;i<clone.length;i++){
                    clone[i].data.values.pk_appdetail={display:null,value:null};
                    datas.push({values:clone[i].data.values});
                }
            }
            this.props.editTable.insertRowsAfterIndex(one, datas,number+1);
        })
        
    }
    /**
     * 插入行事件
     * @param {*} AreaId 
     * @param {*} data 
     * @param {*} index 
     */
    insertLine(AreaId, data, index){
        this.props.editTable.addRow(AreaId,index+1);
    }
    /**
     * 返回按钮事件
     */
    backButtonClick(){
        pubUtil.pushTo(this.props, this.listUrl,{
            appcode: this.props.getSearchParam('c'),
            pagecode: this.listPageCode
        });
    }
    onRef(ref){

    }
    getAssidModalRedner(one,isNeedVersion){
        return{
            label: one.label,
            attrcode: one.attrcode,
            visible: one.visible || false,
            width: one.width || 100,
            itemtype: 'refer',
            render: (text, record, index) =>{
                return (
                    <AssidModalRedner
                         isNeedVersion={isNeedVersion?isNeedVersion:false}
                        voucherdate={record.values.voucherdate.value}
                        onRef={this.onRef}
                       getPretentAssData={()=>{return this.getPretentAssData(one.attrcode, record, index)}}
                       doConfirm={(assid, data, display)=>{this.assidModalRednerDoConfirm(assid, data, one.attrcode, index, display)}}
                    />
                );
            }
        }
    }
    /**
     * 取得辅助核算组件参数
     * @param {*} attrcode 
     * @param {*} record 
     * @param {*} index 
     */
    getPretentAssData(attrcode, record, index){

    }
    /**
     * 辅助核算点击后事件
     * @param {*} assid 
     * @param {*} data 
     * @param {*} one 
     * @param {*} attrcode 
     * @param {*} index 
     * @param {*} display 
     */
    assidModalRednerDoConfirm(assid, data, attrcode, index, display){

    }

    /**
     * 刷新按钮事件
     */
    Refresh(){
        let data = {};
            data[this.formId] = this.props.form.getAllFormValue(this.formId);
            this.listIds.map((one)=>{
                data[one] = this.props.editTable.getAllData(one);
            })
            this.doRefresh(data);
            toast({color:"success",title:this.main.state.json['2002-0008']})
    }
    /**
     * 执行刷新信息
     * @param {*} data 
     */
    doRefresh(data){

    }
    /**
     * 保存新增事件
     */
    SaveAdd(){
        let checkFlag = this.props.form.isCheckNow(this.formId);
        this.listIds.map((one)=>{
            // TODO:平台问题，删除的也进行了合规性校验，导致出错
            // if(!this.props.editTable.getAllRows(one)){
            //     checkFlag = false;
            // }
        })
        if(checkFlag){
            let data = {};
            data[this.formId] = this.props.form.getAllFormValue(this.formId);
            this.listIds.map((one)=>{
                data[one] = this.props.editTable.getAllData(one);
            })
            this.doSaveAdd(data);
        }
    }
    /**
     * 
     * @param {*} data 
     */
    setButtonStatus(buttons,status){
        this.props.button.setButtonDisabled(buttons,status);
    }
    /**
     * 
     * @param {*} data 
     */
    setButtonStatusVisible(buttons,status){
        this.props.button.setButtonVisible(buttons,status);
    }
}
export default CardPageController;